package com.suredy.app.project.ctrl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.suredy.app.project.model.ContractPayment;
import com.suredy.app.project.service.ContractPaymentSrv;

/**
 * 付款信息表单控制器
 * 
 * @author VIVID.G
 * @since 2015-7-30
 * @version v0.1
 */
@Controller
@RequestMapping("/payment/form")
public class PaymentFormCtrl {

	@Autowired
	private ContractPaymentSrv paySrv;

	@RequestMapping(method = RequestMethod.GET)
	public String costForm(String id, String contractId, Model model) {
		String view = "app/project/pay-form";

		if (StringUtils.isBlank(contractId)) {
			model.addAttribute("noContractId", true);
			return view;
		}

		ContractPayment pay = null;

		if (StringUtils.isBlank(id)) {
			// 新建
			pay = new ContractPayment();
		} else {
			// 修改
			pay = this.paySrv.get(id);

			if (pay == null || StringUtils.isBlank(pay.getId())) {
				model.addAttribute("notFound", true);
				return view;
			}
		}

		model.addAttribute("contractId", contractId);
		model.addAttribute("data", pay);

		return view;
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	@ResponseBody
	public boolean saveCostForm(ContractPayment pay) {
		if (pay.getContract() == null)
			return false;

		if (StringUtils.isBlank(pay.getId()))
			pay.setId(null);

		pay = this.paySrv.saveOrUpdate(pay);

		return pay != null && !StringUtils.isBlank(pay.getId());
	}

}
